package mytomcat.core;

import java.io.IOException;
import java.io.OutputStream;

/**
 * <ul>
 * <li>Title:  MyResponse</li>
 * <li>Copyright: Copyright (c) 2018</li>
 * </ul>
 *
 * @author swc
 * @version     V1.0
 * @date 2020/4/20 0020 上午 9:53
 */
public class MyResponse {

    private OutputStream outputStream;

    public MyResponse(OutputStream outputStream) {
        this.outputStream = outputStream;
    }


    public void write(String content,String contentType) throws IOException{
        StringBuffer httpResponse = new StringBuffer();
        contentType = contentType==null||"".equals(contentType.trim())?"text/html":contentType;

        httpResponse.append("HTTP/1.1 200 OK\n")
                .append("Connection: keep-alive");

        if(!"other*".equalsIgnoreCase(contentType)){
            httpResponse.append("Content-Type: "+contentType+"\n");
        }
        httpResponse.append("Access-Control-Allow-Origin: *\n")//防止内部跨域问题
                .append("\r\n")
                .append(content);

        outputStream.write(httpResponse.toString().getBytes());
        outputStream.close();
    }

    public void writeJSon(String content) throws IOException{
        StringBuffer httpResponse = new StringBuffer();
        httpResponse.append("HTTP/1.1 200 OK\n")
                .append("Content-Type: application/json\n")
                .append("Access-Control-Allow-Origin: *\n")//防止内部跨域问题
                .append("\r\n")
                .append(content);
        outputStream.write(httpResponse.toString().getBytes());
        outputStream.close();
    }
}
